package com.zh.junit.service;

import com.zh.junit.dao.Book;
import com.zh.junit.dao.entity.BookEntity;
import com.zh.junit.dao.repository.BookRepository;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @author ZH
 * @date 12:05 2023/2/28
 */
@AllArgsConstructor
@Service
public class BookService {
    private final BookRepository bookRepository;

    /**
     * 添加书
     *
     * @param book
     */
    public Long saveBook(Book book) {
        if(bookRepository.existsByTitle(book.getTitle())){
            throw new IllegalArgumentException("此书名已经重复了");
        }
        BookEntity bookEt = buildBookEntity(book);
        bookEt.setCreateTime(LocalDateTime.now());
        return bookRepository.save(bookEt).getId();
    }

    /**
     * 删除书
     *
     * @param bookId
     */
    public void removeBook(Long bookId) {
        bookRepository.deleteById(bookId);
    }

    /**
     * 更新书
     *
     * @param bookId
     * @param book
     */
    public void updateBook(Long bookId, Book book) {
        //会被null值覆盖
//        BookEntity bookEt = buildBookEntity(book);
//        bookEt.setId(bookId);
        BookEntity bookEt = this.findById(bookId);
        copyField(book, bookEt); //copy不为null的值，避免被null值覆盖

        bookEt.setUpdateTime(LocalDateTime.now());
        //save()方法会先selectByID，再update
        bookRepository.save(bookEt);
    }

    private BookEntity findById(Long bookId) {
        return bookRepository.findById(bookId).orElse(null);
    }

    /**
     * 根据标题搜索书
     *
     * @param keyword
     */
    public List<Book> searchByTitle(String keyword) {
        List<BookEntity> bookEntities = bookRepository.findByTitleLike(keyword);

        return CollectionUtils.collect(bookEntities, this::wrapBook).stream().toList();
    }

    /**
     * 查询全部书
     */
    public List<Book> findAll() {
        Iterable<BookEntity> bookEntities = bookRepository.findAll();
        return CollectionUtils.collect(bookEntities, this::wrapBook).stream().toList();
    }


    private BookEntity buildBookEntity(Book book) {
        BookEntity entity = new BookEntity();
        BeanUtils.copyProperties(book, entity);
        return entity;
    }

    private Book wrapBook(BookEntity entity) {
        Book book = new Book();
        BeanUtils.copyProperties(entity, book);
        return book;
    }

    public static void copyField(Book book, BookEntity entity) {
        BeanUtils.copyProperties(book, entity);
    }
}
